package cn.wolfcode.shop.mq;

import cn.wolfcode.shop.result.CodeMsg;
import com.alibaba.fastjson.JSON;
import org.apache.activemq.ScheduledMessage;
import org.apache.activemq.command.ActiveMQMapMessage;
import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;

@Component
public class MQSender {
    @Autowired
    private JmsTemplate jmsTemplate;

    /**
     * 秒杀成功,发送消息到消息中心的指定的成功消息队列中
     * @param uuid 用来确定要发送个是哪个用户
     * @param codeMsg 需要响应给用户的数据 响应码,订单号,用来显示具体订单
     * @throws JMSException
     */
    public void sendWebSocketMessage(String uuid, CodeMsg codeMsg) throws JMSException {
        MapMessage mapMessage = new ActiveMQMapMessage();
        mapMessage.setObject("uuid",uuid);
        mapMessage.setObject("codeMsg", JSON.toJSONString(codeMsg));
        mapMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY,3*1000);
        jmsTemplate.convertAndSend(MQDestination.WEBSOCKET_QUEUE,mapMessage);
    }

    /**
     * 进入秒杀操作,失败后发送消息到指定的存放失败消息的队列
     * @param orderMessage
     */
    public void sendOrderDQL(OrderMessage orderMessage) throws JMSException {
        ObjectMessage objectMessage = new ActiveMQObjectMessage();
        objectMessage.setObject(orderMessage);
        jmsTemplate.convertAndSend(MQDestination.ORDER_DQL_DESTINATION,objectMessage);
    }

    public void publishCancelLocalSign(Long goodId) throws JMSException {

        jmsTemplate.convertAndSend(new ActiveMQTopic(MQDestination.CANCEL_LOCAL_SIGN_TOPIC),goodId+"");
    }
}
